import json

import requests


def get_xk_token_value(cookie):
    xk_token_value_post_header = {"Cookie": cookie}
    xk_token_value_url = "http://jwcxk2.aufe.edu.cn/student/courseSelect/courseSelect/index"
    try:
        xk_token_value_text = requests.get(xk_token_value_url, headers=xk_token_value_post_header).text
        xk_token_value = xk_token_value_text.split('<input type="hidden" id="tokenValue" value="')[1].split('"/>')[
            0]
        return xk_token_value
    except:
        return ""

def submit_xk_info_from_free_course_list_element(cookie,free_course_list_element):
    temp = free_course_list_element
    kch = temp.split("课程号:")[1].split('#')[0]
    kxh = temp.split("课序号:")[1].split('#')[0]
    jxjhnf = temp.split("教学计划年份:")[1].split('#')[0]

    token_value = get_xk_token_value(cookie)
    if token_value == "":
        return 'error'

    submit_xk_info_post_header = {"Cookie": cookie}
    submit_xk_info_post_data = {
        'dealType': '5',
        'kcIds': '{}@{}@{}'.format(kch, kxh, jxjhnf),
        'kcms': '',
        'fajhh': '4092',
        'sj': '',
        'searchtj': '',
        'kclbdm': '',
        'inputCode': '',
        'tokenValue': token_value
    }
    submit_xk_info_url = "http://jwcxk2.aufe.edu.cn/student/courseSelect/selectCourse/checkInputCodeAndSubmit"
    try:
        submit_xk_info = requests.post(submit_xk_info_url,
                                       headers=submit_xk_info_post_header,
                                       data=submit_xk_info_post_data)
        submit_xk_info_res = json.loads(submit_xk_info.text)
        return submit_xk_info_res["result"]
    except:
        return 'error'